package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//服务器程序
public class UdpEchoServer {
    private DatagramSocket socket;

    //给服务器指定一个端口号
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    //服务器启动运行程序
    public void start() throws IOException {
        System.out.println("服务器启动...");

        //服务器持续运行
        //每次循环处理一次请求
        while(true) {
            //构建请求数据包
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            //获取请求
            socket.receive(requestPacket);//输出型参数

            //解析请求数据包
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());

            //计算响应值
            //这里是回显服务器，直接返回原数据
            String response = process(request);

            //构建响应数据包
            //UDP 不存放对端的源IP 和 源端口，所以需要传入对方的地址
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPacket.getSocketAddress());
            //发送响应数据包
            socket.send(responsePacket);

            //打印日志
            System.out.printf("[%s : %d] request: %s response: %s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }

    //计算响应，服务器的核心代码区域
    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
